import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../core/di/service_locator.dart';
import '../../core/store/redux_qa_manager.dart';
import '../../core/store/redux_social_manager.dart';
import '../../core/store/redux_user_manager.dart';
import '../../core/models/question_entity.dart';
import '../../core/models/social_post_entity.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/widgets/toast_notifications.dart';
import 'qa_detail_page.dart';
import 'social_detail_page.dart';
import 'social_list_page.dart';
import '../publish/publish_page.dart';

/// 问答界面
class VamosQuestionInterface extends StatefulWidget {
  const VamosQuestionInterface({super.key});

  @override
  State<VamosQuestionInterface> createState() => _VamosQuestionInterfaceState();
}

class _VamosQuestionInterfaceState extends State<VamosQuestionInterface> {
  late ReduxQAManager _qaManager;
  late ReduxSocialManager _socialManager;
  late ReduxUserManager _userManager;

  @override
  void initState() {
    super.initState();
    _qaManager = serviceLocator<ReduxQAManager>();
    _socialManager = serviceLocator<ReduxSocialManager>();
    _userManager = serviceLocator<ReduxUserManager>();
  }

  /// 格式化发布时间
  String _formatPostTime(DateTime publishTime) {
    // 格式化为 HH:MM 格式
    final hour = publishTime.hour.toString().padLeft(2, '0');
    final minute = publishTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 导航到问答详情页面
  void _navigateToQADetail(QuestionEntity question) {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosQADetailInterface(question: question),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  /// 导航到社交动态详情页面
  void _navigateToSocialDetail(SocialPostEntity post) {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosSocialDetailInterface(post: post),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  /// 导航到社交动态列表页面
  void _navigateToSocialList() {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosSocialListInterface(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  /// 导航到发布问答页面
  void _navigateToPublishQA() {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosPublishInterface(initialTabIndex: 0),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 固定标题
                _buildTitleSection(),

                SizedBox(height: 10.h),
                // 横向滚动列表标题
                _buildHorizontalListHeader(),

                SizedBox(height: 12.h),

                // 横向滚动列表
                _buildHorizontalScrollList(),

                SizedBox(height: 24.h),

                // Model Q&A 标题和创建按钮
                _buildModelQASection(),

                SizedBox(height: 16.h),

                // 纵向滚动问答列表
                _buildVerticalQAList(),

                SizedBox(height: 120.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建标题区域
  Widget _buildTitleSection() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 0.h, bottom: 0.h),
      child:
          Text(
            'Vamos',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily:
                  GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily,
              fontWeight: FontWeight.bold,
            ),
          ).center(),
    );
  }

  /// 构建横向列表标题
  Widget _buildHorizontalListHeader() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Circle 标题
          Text('Circle')
              .fontSize(20.sp)
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w700).fontFamily,
              )
              .textColor(Colors.white)
              .bold(),

          // View All 和箭头
          Row(
            children: [
              Text('View All').fontSize(14.sp).textColor(Colors.grey[300]),
              SizedBox(width: 4.w),
              Icon(
                Icons.arrow_forward_ios,
                size: 12.w,
                color: Colors.grey[300],
              ),
            ],
          ).inkWell(
            onTap: () {
              _navigateToSocialList();
            },
          ),
        ],
      ),
    );
  }

  /// 构建横向滚动列表
  Widget _buildHorizontalScrollList() {
    return SizedBox(
      height: 252.h,
      child: StreamBuilder(
        stream: _socialManager.store.onChange,
        builder: (context, snapshot) {
          final posts = _socialManager.store.state.socialState.postCollection;

          if (posts.isEmpty) {
            return Center(
              child:
                  Text(
                    'No posts available',
                  ).fontSize(16.sp).textColor(Colors.grey[400]).center(),
            );
          }

          return ListView.builder(
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            itemCount: posts.length,
            itemBuilder: (context, index) {
              return _buildHorizontalItem(posts[index], index);
            },
          );
        },
      ),
    );
  }

  /// 构建横向列表项
  Widget _buildHorizontalItem(SocialPostEntity post, int index) {
    return Container(
      width: 168.w,
      margin: EdgeInsets.only(right: 12.w),
      child: AspectRatio(
        aspectRatio: 168 / 252,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 8,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Stack(
              children: [
                // 背景图片
                Positioned.fill(
                  child:
                      post.mediaType == PostMediaType.image &&
                              post.mediaUrl != null
                          ? Image.asset(
                            post.mediaUrl!,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                color: Colors.grey[300],
                                child:
                                    Icon(
                                      Icons.image,
                                      size: 40.w,
                                      color: Colors.grey[600],
                                    ).center(),
                              );
                            },
                          )
                          : post.mediaType == PostMediaType.video &&
                              post.thumbnailUrl != null
                          ? Image.asset(
                            post.thumbnailUrl!,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                color: Colors.grey[300],
                                child:
                                    Icon(
                                      Icons.video_library,
                                      size: 40.w,
                                      color: Colors.grey[600],
                                    ).center(),
                              );
                            },
                          )
                          : Container(
                            color: Colors.grey[300],
                            child:
                                Icon(
                                  post.mediaType == PostMediaType.video
                                      ? Icons.video_library
                                      : Icons.image,
                                  size: 40.w,
                                  color: Colors.grey[600],
                                ).center(),
                          ),
                ),

                // 右上角菜单图标
                Positioned(
                  top: 8.h,
                  right: 8.w,
                  child: Container(
                    width: 24.w,
                    height: 24.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.3),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.more_vert,
                      size: 16.w,
                      color: Colors.white,
                    ).center().inkWell(
                      onTap: () {
                        _handlePostReport(post);
                      },
                    ),
                  ),
                ),

                // 视频播放图标（如果是视频）
                if (post.mediaType == PostMediaType.video)
                  Positioned(
                    top: 8.h,
                    left: 8.w,
                    child: Container(
                      width: 24.w,
                      height: 24.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.6),
                        shape: BoxShape.circle,
                      ),
                      child:
                          Icon(
                            Icons.play_arrow,
                            size: 16.w,
                            color: Colors.white,
                          ).center(),
                    ),
                  ),

                // 底部半透明遮罩
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    height: 80.h,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.7),
                        ],
                      ),
                    ),
                  ),
                ),

                // 底部内容
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Padding(
                    padding: EdgeInsets.all(12.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 文字内容
                        Text(
                          post.content,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500,
                            height: 1.2,
                          ),
                        ),

                        SizedBox(height: 8.h),

                        // 底部信息行
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            // 时间戳
                            Text(
                              _formatPostTime(post.publishTime),
                              style: TextStyle(
                                color: Colors.white.withOpacity(0.8),
                                fontSize: 12.sp,
                              ),
                            ),

                            // 查看数
                            Row(
                              children: [
                                Image.asset(
                                  'assets/images/eye.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  '${post.likeCount}', // 使用点赞数作为查看数
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.8),
                                    fontSize: 12.sp,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    ).inkWell(
      onTap: () {
        _navigateToSocialDetail(post);
      },
    );
  }

  /// 构建 Model Q&A 区域
  Widget _buildModelQASection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Model Q&A 标题
          Text('Model Q&A')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w700).fontFamily,
              ),

          // 创建按钮
          Container(
            width: 125.w,
            height: 35.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/create_button.png'),
                fit: BoxFit.fill,
              ),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: InkWell(
              onTap: () {
                _navigateToPublishQA();
              },
              borderRadius: BorderRadius.circular(20.r),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建纵向问答列表
  Widget _buildVerticalQAList() {
    return StreamBuilder(
      stream: _qaManager.store.onChange,
      builder: (context, snapshot) {
        final questions = _qaManager.store.state.qaState.questionCollection;

        if (questions.isEmpty) {
          return Container(
            height: 200.h,
            child: Center(
              child:
                  Text(
                    'No questions available',
                  ).fontSize(16.sp).textColor(Colors.grey[400]).center(),
            ),
          );
        }

        return ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount: questions.length,
          itemBuilder: (context, index) {
            return _buildVerticalQAItem(questions[index], index);
          },
        );
      },
    );
  }

  /// 构建纵向问答项
  Widget _buildVerticalQAItem(QuestionEntity question, int index) {
    // 根据authorId获取用户信息
    final user = _userManager.getUserById(question.authorId);

    return Container(
      width: 343.w,
      margin: EdgeInsets.only(bottom: 16.h),
      child: AspectRatio(
        aspectRatio: 343 / 260,
        child: Stack(
          children: [
            // 底部背景图片和内容
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                width: 343.w,
                child: Stack(
                  children: [
                    // 背景图片
                    Image.asset(
                      'assets/images/question_card_bg.png',
                      width: 343.w,
                      fit: BoxFit.fitWidth,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          height: 120.h,
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                        );
                      },
                    ),

                    // 内容区域
                    Positioned.fill(
                      child: Padding(
                        padding: EdgeInsets.only(
                          left: 180.w,
                          right: 16.w,
                          bottom: 50.h,
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Spacer(),
                            // 问题标题
                            Text(
                              question.title,
                              maxLines: 4,
                              overflow: TextOverflow.ellipsis,
                            ).fontSize(12.sp).textColor(Colors.white).bold(),

                            Spacer(),

                            // 用户信息
                            Row(
                              children: [
                                // 用户头像
                                Container(
                                  width: 50.w,
                                  height: 50.w,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: Colors.white,
                                      width: 1,
                                    ),
                                  ),
                                  child: ClipOval(
                                    child:
                                        user != null
                                            ? Image.asset(
                                              user.profileImage,
                                              width: 50.w,
                                              height: 50.w,
                                              fit: BoxFit.cover,
                                              errorBuilder: (
                                                context,
                                                error,
                                                stackTrace,
                                              ) {
                                                return Icon(
                                                  Icons.person,
                                                  size: 12.w,
                                                  color: Colors.grey[600],
                                                ).center();
                                              },
                                            )
                                            : Icon(
                                              Icons.person,
                                              size: 12.w,
                                              color: Colors.grey[600],
                                            ).center(),
                                  ),
                                ),

                                SizedBox(width: 8.w),

                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,

                                  children: [
                                    //用户名
                                    Text(
                                      user?.displayName ?? 'Unknown User',
                                    ).fontSize(15.sp).textColor(Colors.white),
                                    //用户签名
                                    Container(
                                      constraints: BoxConstraints(
                                        maxWidth: 80.w,
                                      ),
                                      child: Text(
                                        user?.personalBio ?? 'No bio available',
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: Colors.grey[400],
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            Spacer(),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            // 左上角问答图片
            Positioned(
              top: 0,
              left: 0,
              child: Container(
                width: 155.w,
                height: 205.h,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child: Stack(
                    children: [
                      // 媒体内容
                      if (question.mediaType == QAMediaType.image &&
                          question.mediaUrl != null)
                        Image.asset(
                          question.mediaUrl!,
                          width: 155.w,
                          height: 205.h,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return Container(
                              color: Colors.grey[300],
                              child:
                                  Icon(
                                    Icons.image,
                                    size: 40.w,
                                    color: Colors.grey[600],
                                  ).center(),
                            );
                          },
                        )
                      else if (question.mediaType == QAMediaType.video &&
                          question.thumbnailUrl != null)
                        Image.asset(
                          question.thumbnailUrl!,
                          width: 155.w,
                          height: 205.h,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return Container(
                              color: Colors.grey[300],
                              child:
                                  Icon(
                                    Icons.video_library,
                                    size: 40.w,
                                    color: Colors.grey[600],
                                  ).center(),
                            );
                          },
                        )
                      else
                        Container(
                          color: Colors.grey[300],
                          child:
                              Icon(
                                question.mediaType == QAMediaType.video
                                    ? Icons.video_library
                                    : Icons.quiz,
                                size: 40.w,
                                color: Colors.grey[600],
                              ).center(),
                        ),

                      // 视频播放图标
                      if (question.mediaType == QAMediaType.video)
                        Container(
                          width: 155.w,
                          height: 205.h,
                          child:
                              Icon(
                                Icons.play_circle_filled,
                                size: 48.w,
                                color: Colors.white.withOpacity(0.8),
                              ).center(),
                        ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    ).inkWell(
      onTap: () {
        _navigateToQADetail(question);
      },
    );
  }

  /// 处理动态举报
  void _handlePostReport(SocialPostEntity post) {
    showVamosReportDialog(
      context: context,
      title: 'Report Post',
      subtitle: 'Please select a reason for reporting this post.',
      onReportSubmitted: (VamosReportOption option) {
        _deletePostAndExit(post);
      },
    );
  }

  /// 删除动态并返回
  void _deletePostAndExit(SocialPostEntity post) async {
    try {
      final socialManager = serviceLocator<ReduxSocialManager>();
      final success = await socialManager.deletePost(post.postId);
      if (success) {
        ToastNotificationHelper.showSuccessToast(
          context,
          message: 'You won\'t see this again.',
        );
        // 不需要返回，因为列表会自动更新
      } else {
        ToastNotificationHelper.showErrorToast(
          context,
          message: 'Failed to report post.',
        );
      }
    } catch (e) {
      ToastNotificationHelper.showErrorToast(
        context,
        message: 'Error reporting post: $e',
      );
    }
  }
}
